﻿/*
LICENCE___________________________________________________________________
    Copyright (C) 2012 Reverdy Sylvain

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License along
    with this program; if not, write to the Free Software Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
FIN LICENCE______________________________________________________________
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Input;
using Merise_designer.Methodes;
using Merise_designer.UItools;
using System.ComponentModel;

namespace Merise_designer.Objets
{
    public class CL_Entite
    {
        #region Attributs
        private DataGrid entite;
        private string idEntite;
        private string name;
        private TextBlock title = new TextBlock();
        private string codeName;
        private System.Windows.Shapes.Rectangle[] poignee = new System.Windows.Shapes.Rectangle[4];
        private string namePoignee = Configuration.namePoignee;
        private double entLarg = 150 - (150 % Configuration.stepGrid), entHaut = 92 - (92 % Configuration.stepGrid);
        private double pLarg = 7, pHaut = 7; //Largueur et hauteur des la poignées de sélection
        private double pLargR = 7, pHautR = 7; //Largueur et hauteur de la poignée de redimentionnement
        public Methodes.ObjetsCommun controller;
        #endregion

        #region Construction
        public CL_Entite() { }
        public CL_Entite(Methodes.ObjetsCommun contructor, Grid grille, string id, string nom, string codeNom, double hauteur, double largeur, Point position)
        {
            //Instanciation
            this.controller = contructor;
            entite = new System.Windows.Controls.DataGrid();

            this.idEntite = id;
            this.name = nom;
            title.Text = nom;
            this.codeName = codeNom;
            entite.Name = id;

            //taille Style
            entite.Width = largeur;
            entite.Height = hauteur;

            this.createEntite(grille, position);
        }
        public CL_Entite(Methodes.ObjetsCommun contructor, Grid grille, string id, Point position)
        {
            //Instanciation
            this.controller = contructor;
            entite = new System.Windows.Controls.DataGrid();

            this.idEntite = id;
            this.name = id;
            title.Text = id;
            this.codeName = id.ToUpper();
            entite.Name = id;

            //taille Style
            entite.Width = entLarg;
            entite.Height = entHaut;

            this.createEntite(grille, position);
        }
        private void createEntite(Grid grille, Point position)
        {
            title.Name = CL_Variables.getTitleName() + idEntite;

            //style
            //entite.IsEnabled = false;
            entite.SelectedCellsChanged += new SelectedCellsChangedEventHandler(mouseClick);

            entite.HorizontalAlignment = HorizontalAlignment.Left;
            entite.VerticalAlignment = VerticalAlignment.Top;
            entite.BorderBrush = System.Windows.Media.Brushes.Black;
            entite.Background = System.Windows.Media.Brushes.White;
            entite.RowBackground = System.Windows.Media.Brushes.White;
            this.entite.RowHeaderWidth = 0;

            this.entite.SelectionMode = DataGridSelectionMode.Single;
            this.entite.CanUserReorderColumns = false;
            this.entite.IsManipulationEnabled = false;
            this.entite.CanUserResizeColumns = false;
            this.entite.CanUserSortColumns = false;
            this.entite.GridLinesVisibility = DataGridGridLinesVisibility.None;
            this.entite.IsManipulationEnabled = false;
            this.entite.HeadersVisibility = DataGridHeadersVisibility.Row;
            this.entite.FontSize = 9;
            this.entite.IsReadOnly = true;
            this.entite.ColumnWidth = DataGridLength.SizeToCells;

            title.TextAlignment = TextAlignment.Center;
            title.HorizontalAlignment = HorizontalAlignment.Left;
            title.VerticalAlignment = VerticalAlignment.Top;
            this.title.Background = System.Windows.Media.Brushes.Transparent;

            //position
            ThicknessConverter myThicknessConverter = new ThicknessConverter();
            Thickness th1;

            th1 = (Thickness)myThicknessConverter.ConvertFromString(position.X + " " + position.Y + " 0 0");
            entite.Margin = th1;
            this.setTitlePosition();

            //colonnes
            entite.HeadersVisibility = DataGridHeadersVisibility.None;

            //Créé et ajoute l'objet à la grille
            grille.Children.Add(entite);
            grille.Children.Add(title);

            //menu contextuel
            ContextMenu mainMenu = new ContextMenu();
            entite.ContextMenu = mainMenu;
            this.title.ContextMenu = mainMenu;

            MenuItem item1 = new MenuItem();
            item1.Header = "Edit";
            item1.Foreground = Brushes.Black;
            item1.Background = Brushes.Transparent;
            item1.Click += new RoutedEventHandler(edition);
            mainMenu.Items.Add(item1);

            MenuItem item2 = new MenuItem();
            item2.Header = "Convert to association";
            item2.Foreground = Brushes.Black;
            item2.Background = Brushes.Transparent;
            item2.Click += new RoutedEventHandler(convertToEntity);
            mainMenu.Items.Add(item2);
        }
        #endregion

        #region Menus
        public void edition(object sender, RoutedEventArgs e)
        {
            Edition myF = new Edition(this.controller);
            myF.AfficherEntite(this, this.controller);
        }//item du menu
        private void convertToEntity(object sender, RoutedEventArgs e)
        {
            this.controller.convertToAssociation(this);
        }//Item du menu

        #endregion

        #region opérations
        //Click dans le dataGrid
        void mouseClick(object sender, SelectedCellsChangedEventArgs e)
        {
            entite.UnselectAll();
        }

        public void move(Point from, Point to)
        {

            ThicknessConverter myThicknessConverter = new ThicknessConverter();
            Thickness th1;
            double x = entite.Margin.Left + to.X - from.X;
            double y = entite.Margin.Top + to.Y - from.Y;
            Point p = new Point(x, y);
            p = Tools.SnapPointToGrid(p, Configuration.stepGrid);
            if (p.X < 0) p.X = 0;
            if (p.Y < 0) p.Y = 0;

            th1 = (Thickness)myThicknessConverter.ConvertFromString(p.X + " " + p.Y + " 0 0");
            entite.Margin = th1;

            this.setTitlePosition();

            DelPoignees((Grid)entite.Parent);
            addPoignees((Grid)entite.Parent);
        }
        public void Supprimer(Grid grille)
        {
            //Supprime la ligne de la grille parente
            grille.Children.Remove(this.entite);
            grille.Children.Remove(this.title);
        }
        public void getFocus(Grid grille)
        {
            //entite.BorderBrush = System.Windows.Media.Brushes.Blue;
            addPoignees(grille);
        }
        public void lostFocus(Grid grille)
        {
            entite.SelectedIndex = -1;
            entite.BorderBrush = System.Windows.Media.Brushes.Black;
            DelPoignees(grille);
        }
        public void afficheContenu(List<CL_DictionnaireDeDonnees> contenu)
        {
            if (Configuration.affichache_noms_pasCode) title.Text = name;
            if (!Configuration.affichache_noms_pasCode) title.Text = codeName;

            if (contenu.Count > 0)
            {

                contenu.Sort(CL_DictionnaireDeDonnees.idComparaison);

                this.entite.ItemsSource = contenu;

                //SortDescription sortDescription = new SortDescription("id", ListSortDirection.Ascending); ;
                //this.entite.Columns[1].SortDirection = ListSortDirection.Ascending;
                //this.entite.Items.SortDescriptions.Add(sortDescription);

                this.entite.UpdateLayout();
                this.entite.Columns[0].Visibility = Visibility.Hidden;
                this.entite.Columns[1].Visibility = Visibility.Hidden;
                if (Configuration.affichache_noms_pasCode) this.entite.Columns[3].Visibility = Visibility.Hidden;
                if (!Configuration.affichache_noms_pasCode) this.entite.Columns[2].Visibility = Visibility.Hidden;
                this.entite.Columns[4].Visibility = Visibility.Hidden;
                this.entite.Columns[6].Visibility = Visibility.Hidden;
                this.entite.Columns[7].Visibility = Visibility.Hidden;
                this.entite.Columns[8].Visibility = Visibility.Hidden;
                this.entite.Columns[9].Visibility = Visibility.Hidden;
                this.entite.Columns[11].Visibility = Visibility.Hidden;


                //Style des clé primaires
                for (int i = 0; i < contenu.Count; i++)
                {
                    if (contenu[i].pk)
                    {
                        DataGridRow r = (DataGridRow)this.entite.ItemContainerGenerator.ContainerFromIndex(i);
                        if (r != null) r.FontWeight = FontWeights.Bold;
                    }

                }
                //Tri des colonnes

                if (Mode.mode == Mode.MODE_MLD)
                {
                    //change le style pour les clés étrangères
                    for (int i = 0; i < contenu.Count; i++)
                    {
                        if (contenu[i].idEntite == null || contenu[i].idEntite != idEntite)
                        {
                            DataGridRow r = (DataGridRow)this.entite.ItemContainerGenerator.ContainerFromIndex(i);
                            r.FontStyle = FontStyles.Italic;
                        }
                    }

                }

            }
            else
            {
                entite.UpdateLayout();
                this.entite.ItemsSource = "";
            }
        }

        private void setTitlePosition()
        {
            title.Width = entite.Width;
            title.Height = 20;

            ThicknessConverter myThicknessConverter = new ThicknessConverter();
            Thickness th1;

            double posX = this.entite.Margin.Left;
            double posY = this.entite.Margin.Top - this.title.Height;

            th1 = (Thickness)myThicknessConverter.ConvertFromString(posX + " " + posY + " 0 0");

            this.title.Margin = th1;

        }
        #endregion

        #region accesseurs
        public string Id
        {
            get
            {
                return this.idEntite;
            }
        }
        public string Name
        {
            get
            {
                return this.name;
            }
            set
            {
                this.name = value;
                this.title.Text = value;
            }
        }
        public string CodeName
        {
            get
            {
                return this.codeName;
            }
            set
            {
                this.codeName = value;
            }
        }
        public double Largeur
        {
            set { entite.Width = value; }
            get
            {
                return entite.Width;
            }
        }
        public double Hauteur
        {
            set
            {
                entite.Height = value;
            }
            get
            {
                return entite.Height;
            }
        }
        public double posLeft
        {
            get
            {
                return entite.Margin.Left;
            }
        }
        public double posTop
        {
            get
            {
                return entite.Margin.Top;
            }
        }
        public Point center
        {
            get
            {
                int X = Convert.ToInt32(this.posLeft + (entite.Width / 2));
                int Y = Convert.ToInt32(this.posTop + (entite.Height / 2));
                Point p = new Point(X, Y);
                return p;
            }
        }
        #endregion

        #region Poignées de sélection
        public void addPoignees(Grid grille)
        {
            ThicknessConverter myThicknessConverter = new ThicknessConverter();
            Thickness th;

            for (int i = 0; i < poignee.Count(); i++)
            {
                poignee[i] = new System.Windows.Shapes.Rectangle();
                poignee[i].Name = namePoignee + i.ToString();

                poignee[i].Stroke = System.Windows.Media.Brushes.Black;
                poignee[i].Fill = System.Windows.Media.Brushes.WhiteSmoke;
                poignee[i].HorizontalAlignment = HorizontalAlignment.Left;
                poignee[i].VerticalAlignment = VerticalAlignment.Top;
                poignee[i].Height = pHaut;
                poignee[i].Width = pLarg;
                th = (Thickness)myThicknessConverter.ConvertFromString("0 0 0 0");
                poignee[0].Margin = th;

                grille.Children.Add(poignee[i]);
            }

            //haut gauche
            th = (Thickness)myThicknessConverter.ConvertFromString((entite.Margin.Left - pLarg / 2) + " " + (entite.Margin.Top - pHaut / 2) + " 0 0");
            poignee[0].Margin = th;
            //haut droite
            th = (Thickness)myThicknessConverter.ConvertFromString((entite.Margin.Left + entite.Width - pLarg / 2) + " " + (entite.Margin.Top - pHaut / 2) + " 0 0");
            poignee[1].Margin = th;
            //bas gauche
            th = (Thickness)myThicknessConverter.ConvertFromString((entite.Margin.Left - pLarg / 2) + " " + (entite.Margin.Top + entite.Height - pHaut / 2) + " 0 0");
            poignee[2].Margin = th;
            //bas groite
            th = (Thickness)myThicknessConverter.ConvertFromString((entite.Margin.Left + entite.Width - pLargR) + " " + (entite.Margin.Top + entite.Height - pHautR) + " 0 0");
            poignee[3].Margin = th;
            poignee[3].Fill = System.Windows.Media.Brushes.Black;
            poignee[3].Height = pHautR;
            poignee[3].Width = pLargR;
        }
        public void movePoignees(Point newCursor)
        {
            double nW = (newCursor.X - entite.Margin.Left);
            double nH = (newCursor.Y - entite.Margin.Top);

            if (nW < 50) { nW = 50; };
            if (nH < 50) { nH = 50; };

            entite.Width = nW;
            entite.Height = nH;

            DelPoignees((Grid)entite.Parent);
            addPoignees((Grid)entite.Parent);

            this.setTitlePosition();
        }
        public void DelPoignees(Grid grille)
        {
            for (int i = 0; i < poignee.Count(); i++)
            {
                grille.Children.Remove(this.poignee[i]);
            }
        }
        public int getIDofPoigneeSelect(Point cursor)
        {
            for (int i = 0; i < poignee.Count(); i++)
                if (cursor.X >= poignee[i].Margin.Left & cursor.X <= poignee[i].Margin.Left + poignee[i].Width)
                {
                    if (cursor.Y >= poignee[i].Margin.Top & cursor.Y <= poignee[i].Margin.Top + poignee[i].Height)
                    {
                        return i;
                    }
                }
            return -1;
        }
        #endregion

    }
}
